package com.example.administrator.kotiln.ui;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;

import com.example.administrator.kotiln.R;
import com.example.administrator.kotiln.utils.ToastUtils;
import com.example.administrator.kotiln.utils.Utility;
import com.example.administrator.kotiln.websocket.ServerConnection;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/11/17 0017.
 * 抽出来的websocket请求
 */

public class WebSocketActivity extends AppCompatActivity implements ServerConnection.ServerListener {
    private final String SERVER_URL = "ws://192.168.1.240:9505/";
    private ServerConnection mServerConnection;

    @Bind(R.id.server_connection_status)
    TextView mConnectionStatus;

    @Bind(R.id.message_from_server)
    TextView mMessageFromServer;

    @Bind(R.id.send_message_button)
    Button mSendMessageButton;

    int mCounter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utility.setActionBar(this);
        setContentView(R.layout.activity_websocket);
        ButterKnife.bind(this);
        mServerConnection = new ServerConnection(SERVER_URL);
        mSendMessageButton.setEnabled(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mServerConnection.connect(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mServerConnection.disconnect();
    }


    @OnClick(R.id.send_message_button)
    public void onSendClicked() {
        mServerConnection.sendMessage(String.valueOf(mCounter++));
    }

    @Override
    public void onNewMessage(String message) {
        mMessageFromServer.setText(message);
    }


    @Override
    public void onStatusChange(ServerConnection.ConnectionStatus status) {

        String statusMsg = (status == ServerConnection.ConnectionStatus.CONNECTED ?
                getString(R.string.connected) : getString(R.string.disconnected));
        ToastUtils.showToast(WebSocketActivity.this, statusMsg);
        mConnectionStatus.setText(statusMsg);
        mSendMessageButton.setEnabled(status == ServerConnection.ConnectionStatus.CONNECTED);
    }
}
